<template>
  <div ref="barChartRef" class="w-1/1 h-1/1"></div>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import echarts from "@/plugins/echarts";
const barChartRef = ref<ElRef>();
let echartRef: Nullable<echarts.ECharts> = null;

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  //   显示数据格式化
  formatter: {
    type: String,
    default: "",
  },
  options: {
    type: Object,
    default() {
      return {};
    },
  },
});
watch(
  () => props.options,
  () => {
    setOptions();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});
onUnmounted(() => {
  echartRef?.dispose;
});
const initChart = () => {
  if (unref(barChartRef) && props.options) {
    echartRef = echarts.init(unref(barChartRef) as unknown as HTMLElement);
    setOptions();
    window.onresize = function () {
      echartRef?.resize();
    };
  }
};

const setOptions = () => {
  if (unref(barChartRef) && props.options) {
    const labelOption: any = {
      show: true,
      // position: "insideBottom",
      distance: 15,
      align: "left",
      verticalAlign: "middle",
      rotate: 90,
      formatter: "{c}  {name|{a}}",
      fontSize: 16,
      rich: {
        name: {},
      },
    };
    const _seriesData: any = [];
    const _legendData: any = [];
    if (props.options.seriesData && props.options.seriesData.length > 0) {
      props.options.seriesData.forEach((item: any) => {
        _legendData.push(item.name);
        _seriesData.push({
          name: item.name,
          type: "bar",
          barGap: 0,
          label: labelOption,
          emphasis: {
            focus: "series",
          },
          data: item.data,
        });
      });
    }

    const _echartOption: EChartsOption = {
      title: {
        text: props.title,
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "10px",
        right: "100px",
        bottom: "0",
        containLabel: true,
      },
      legend: {
        top: '40px',
        orient: "vertical",
        left: "right",
        data: _legendData,
      },
      xAxis: [
        {
          type: "category",
          axisTick: { show: false },
          data: props.options.xAxisData,
        },
      ],
      yAxis: [
        {
          type: "value",
        },
      ],
      series: _seriesData,
    };
    echartRef?.setOption(_echartOption);
  }
};
</script>
